package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author: taft
 * @Date: 2018-10-10 11:41
 */
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;


    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy, Boolean desc, String key) {


        //分页查询
        PageHelper.startPage(page,rows);

        //自定义查询条件
        Example example = new Example(Brand.class);

        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(key)){
            criteria.andEqualTo("letter",key);
        }

        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+ (desc?" DESC":" ASC"));//
        }

        //要么使用PageInfo，要么直接转，自动统计总的条目数
       Page<Brand> brandPage = (Page<Brand>) brandMapper.selectByExample(example);


        return new PageResult<Brand>(brandPage.getTotal(),new Long(brandPage.getPages()),brandPage.getResult());
    }

    public void save(Brand brand, List<Long> cids) {

        //先保存brand，然后brandid会自动回显
        this.brandMapper.insertSelective(brand);

        //根据回显的brandid去保存brand和category的中间关系表
        cids.forEach(cid->this.brandMapper.insertBrandCategory(brand.getId(),cid));

    }

    @Transactional
    public void update(Brand brand, List<Long> cids) {

        //先删除品牌和分类的关联关系
        cids.forEach(cid->this.brandMapper.deleteBrandCategoryByBrandId(brand.getId()));

        //修改brand表本身
        this.brandMapper.updateByPrimaryKey(brand);

        //根据brandid去保存brand和category的中间关系表
        cids.forEach(cid->this.brandMapper.insertBrandCategory(brand.getId(),cid));
    }

    public Brand queryBrandById(Long brandId) {
        return this.brandMapper.selectByPrimaryKey(brandId);
    }

    public List<Brand> queryBrandByCategory(Long cid) {


        return this.brandMapper.queryBrandByCategory(cid);
    }

    public List<Brand> queryBrandByIds(List<Long> ids) {
        return this.brandMapper.selectByIdList(ids);
    }
}
